package com.yc.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author zwei
 * @create 2024-09-03 16:59
 */
@Component
@Slf4j
public class JwtTokenUtil {
    private String key="weiweiweiweiweiweiweiweiweiweiweiweiweiweiweiweiweiweiweiweiweiweiweiweiweiweiweiwei";
    public static final long EXPIRE=1000*24*60*60;  //token过期时间1天
    //测试时，此时间改为1秒 再改长一点看是否过期
    public String encodeJWT(Map payloadMap){
        //1.定义hander部分内容
        Map headerMap=new HashMap();
        headerMap.put("alg", SignatureAlgorithm.HS256.getValue());
        headerMap.put("typ","JWT");
        Date date=new Date(System.currentTimeMillis()+EXPIRE);  //过期时间
        payloadMap.put("expiration",date);  //过期时间放入载荷中
        //生成token
        String jwtToken= Jwts.builder().setHeaderParams(headerMap)
                .setClaims(payloadMap)
                .setSubject("user")
                .setIssuedAt(new Date())
                .setExpiration(date)
                .signWith(SignatureAlgorithm.HS256,key)
                .compact();     //拼接header+payload
        return jwtToken;
    }
    public Claims decodeJWTWithkey(String JWTToken){
        try {
            Claims claims=Jwts.parser().setSigningKey(key).parseClaimsJws(JWTToken).getBody();
            return claims;
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("error: token已过期！");
        }
        return null;
    }
    public boolean validateToken(String token,String username){
        return username.equals(decodeJWTWithkey(token).getSubject())&&!isTokenExpired(token);

    }
    //判断token是否过期
    public boolean isTokenExpired(String token){
        if (token==null||token.isEmpty()){    //token为空
            log.error("JWT is empty");
            return true;
        }
        try {                                                       //claims  载荷中的字段
            Date time=new Date(Long.parseLong(decodeJWTWithkey(token).get("expiration").toString()));
            return time.before(new Date());
        }catch (Exception e){
            log.error(e.getMessage());
            return true;
        }
    }






    //其中key是盐  jsonwebtoken的jar包规定  key必须字节数要大于大于你所用的加密算法的最小字节数
    //这里使用的是HS256  最小的key长度规定就是256
    public static String encodeJWT(String key){
        //1.定义header部分内容
        Map headerMap=new HashMap();
        headerMap.put("alg", SignatureAlgorithm.HS256.getValue());
        headerMap.put("typ","JWT");
        //2.定义payload部分内容
        Map payloadMap=new HashMap();
        payloadMap.put("sub","测试jwt生成token");
        payloadMap.put("iat", UUID.randomUUID());
        payloadMap.put("exp",System.currentTimeMillis()+1);  //过期时间
        payloadMap.put("name","wei");
        payloadMap.put("role","admin");
        //3生成token
        String jwtToken= Jwts.builder().setHeaderParams(headerMap)
               .setClaims(payloadMap)
               .signWith(SignatureAlgorithm.HS256,key)
               .compact();     //拼接header+payload
        return jwtToken;
    }
    public static void decodeJWT(String JWTToken,String key){
        try {
            Claims claims=Jwts.parser().setSigningKey(key).parseClaimsJws(JWTToken).getBody();
            Object sub=claims.get("sub");
            Object iat=claims.get("iat");
            Object exp=claims.get("exp");
            Object name=claims.get("name");
            Object role=claims.get("role");
            System.out.println("sub:"+sub+"\nname:"+name.toString()+"\nrole:"+role+"\nexp:"+exp+"\niat:"+iat+"\n失效了？"
                    +((System.currentTimeMillis()-(long) exp)>0));
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("error: token失效了");
        }
    }
}
